<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { NCard, NForm, NGrid, NFormItemGi, NInput, NTreeSelect, NImage, NAvatar, NSelect, NDatePicker, NRadioGroup, NRadio, NButton, NSpace, NUpload, useNotification } from 'naive-ui'
import type { FormInst, FormRules, FormItemRule, UploadCustomRequestOptions, UploadFileInfo } from 'naive-ui'

import { useDictStore } from '@/stores/dictStore'
import { useUserStore, type UserInfo } from '@/stores/userStore'
import { useOrgStore } from '@/stores/orgStore'

import http from '@/tools/http'

const userStore = useUserStore()
const dictStore = useDictStore()
const orgStore = useOrgStore()
const notification = useNotification()

const formRef = ref<FormInst | null>(null)
const formData = reactive<UserInfo>({
    userId: "",
    orgCode: "",
    userName: "",
    idType: "00",
    idCode: "",
    idBeginDate: undefined,
    idExpDate: undefined,
    birthday: undefined,
    sex: "0",
    nationality: "00",
    telephone: "",
    email: "",
    address: "",
    userAvatar: "",
    remark: ""
})

const formRules: FormRules = ({
    userId: {
        required: true,
        message: '请生成用户编号(账号)',
        trigger: ['input']
    },
    orgCode: {
        required: true,
        message: '请选择机构',
        trigger: ['input']
    },
    userName: {
        required: true,
        message: '请输入姓名',
        trigger: ['input']
    },
    idType: {
        required: true,
        message: '请选择证件类型',
        trigger: ['input']
    },
    idCode: {
        required: true,
        trigger: ['input'],
        validator: (rule: FormItemRule, value: string): boolean | Error => {
            if (formData.idType === '00') {
                const regex = /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
                if (!value || value.length === 0) {
                    return new Error("请输入证件号码")
                }
                if (!regex.test(value)) {
                    return new Error("证件号码格式错误，请重新输入")
                }
            }
            return true
        }
    },
    birthday: {
        required: true,
        message: '请选择出生日期',
        trigger: ['input']
    },
    sex: {
        required: true,
        message: '请选择性别',
        trigger: ['input']
    },
    nationality: {
        required: true,
        message: '请选择民族',
        trigger: ['input']
    }
})

const title = ref("个人信息")

onMounted(() => {
    getUserInfo()
})

function openUserInfoEdit() {
    title.value = "个人信息 - 修改"
}

function cancelUserInfoEdit() {
    title.value = "个人信息"
}

function beforeUpload(data: {
    file: UploadFileInfo
    fileList: UploadFileInfo[]
}) {
    if (data.file.file && data.file.file.size >= 3 * 1024 * 1024) {
        notification.warning({
            content: '头像添加失败',
            meta: '文件大小不得大于3M',
            duration: 2500,
            keepAliveOnHover: true
        })
        return false
    }
}

function getUserInfo() {
    formData.userId = userStore.userDetails.userId
    formData.orgCode = userStore.userDetails.orgCode
    formData.accountStatus = userStore.userDetails.accountStatus
    formData.userName = userStore.userDetails.userName
    formData.idType = userStore.userDetails.idType
    formData.idCode = userStore.userDetails.idCode
    formData.idBeginDate = userStore.userDetails.idBeginDate
    formData.idExpDate = userStore.userDetails.idExpDate
    formData.birthday = userStore.userDetails.birthday
    formData.sex = userStore.userDetails.sex
    formData.nationality = userStore.userDetails.nationality
    formData.telephone = userStore.userDetails.telephone
    formData.email = userStore.userDetails.email
    formData.address = userStore.userDetails.address
    formData.userAvatar = userStore.userDetails.userAvatar
    formData.remark = userStore.userDetails.remark
}

function uploadFile({ file, data, headers, withCredentials, action, onFinish, onError, onProgress }: UploadCustomRequestOptions) {
    const request = new FormData()
    request.append('file', file.file as File, file.file?.name)
    http.post("/static/file/upload", request, {
        headers: {
            'Content-Type': 'multipart/form-data;charset=UTF-8'
        },
        onUploadProgress: function (uploadEvent) {
            if (uploadEvent.total) {
                const progress = uploadEvent.loaded / uploadEvent.total * 100
                onProgress({ percent: Math.ceil(progress) })
            }
        }
    }).then(({ data }) => {
        if (data.code === '0') {
            formData.userAvatar = data.data
            onFinish()
        } else {
            onError()
        }
    })
}

function deleteUserAvatar() {
    formData.userAvatar = ""
}

function submit() {
    formRef.value?.validate((errors) => {
        if (!errors) {
            http.post("/user/update", formData).then(({ data }) => {
                if (data.code === "0") {
                    notification['success']({
                        content: '修改成功',
                        meta: `${data.msg}`,
                        duration: 2500,
                        keepAliveOnHover: true
                    })
                    userStore.loadUserInfo()
                }
            })
        }
    })
    title.value = "个人信息"
}
</script>

<template>
    <div class="flame-container">
        <n-card :title="title" :content-style="{ overflowY: 'auto' }" :bordered="false">
            <n-form ref="formRef" :disabled="title === '个人信息'" :model="formData" :rules="formRules" label-width="116px"
                label-placement="left" require-mark-placement="left">
                <n-grid :cols="2" :x-gap="12">
                    <n-form-item-gi :span="1" label="头像">
                        <n-space>
                            <n-image width="100" height="100" style="border-radius:3px"
                                v-if="formData.userAvatar !== null && formData.userAvatar !== ''"
                                :src="formData.userAvatar" />
                            <n-avatar v-if="formData.userAvatar === null || formData.userAvatar === ''"
                                :style="{ width: '100px', height: '100px', fontSize: '41px', color: '#1890ff', backgroundColor: '#efefef', fontWeight: 'bolder' }">
                                {{ formData.userName.substring(0, 1) }}
                            </n-avatar>
                            <n-upload accept="image/*" :custom-request="uploadFile" :on-remove="deleteUserAvatar"
                                :on-before-upload="beforeUpload" :show-retry-button="false" :max="1">
                                <n-button>上传头像</n-button>
                            </n-upload>
                            <n-button :disabled="title === '个人信息'" @click="formData.userAvatar = ''">清空头像</n-button>
                        </n-space>
                    </n-form-item-gi>
                    <n-form-item-gi :span="1" label="所属机构" path="orgCode">
                        <n-tree-select v-model:value="formData.orgCode" :options="orgStore.orgInfoTree" default-value=""
                            placeholder="请选择所属机构" clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="1" label="姓名" path="userName">
                        <n-input v-model:value="formData.userName" placeholder="请输入姓名" clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="1" label="性别" path="sex">
                        <n-radio-group v-model:value="formData.sex" name="radiogroup">
                            <n-space>
                                <n-radio v-for="dict in dictStore.dict('SEX')" :key="dict.value" :value="dict.value">
                                    {{ dict.label }}
                                </n-radio>
                            </n-space>
                        </n-radio-group>
                    </n-form-item-gi>
                    <n-form-item-gi :span="1" label="民族" path="nationality">
                        <n-select v-model:value="formData.nationality" :options="dictStore.dict('NATIONALITY')"
                            placeholder="请选择民族" clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="1" label="出生日期" path="birthday">
                        <n-date-picker style="width:100%" v-model:formatted-value="formData.birthday"
                            value-format="yyyy-MM-dd" placeholder="请选择出生日期" clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="1" label="证件类型" path="idType">
                        <n-select v-model:value="formData.idType" :options="dictStore.dict('ID_TYPE')" placeholder="请选择证件类型"
                            clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="1" label="证件号码" path="idCode">
                        <n-input v-model:value="formData.idCode" placeholder="请输入证件号码" clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="1" label="证件开始日期" path="idBeginDate">
                        <n-date-picker style="width:100%" v-model:formatted-value="formData.idBeginDate"
                            value-format="yyyy-MM-dd" placeholder="请选择证件开始日期" clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="1" label="证件结束日期" path="idExpDate">
                        <n-date-picker style="width:100%" v-model:formatted-value="formData.idExpDate"
                            value-format="yyyy-MM-dd" placeholder="请选择证件结束日期" clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="1" label="手机号" path="telephone">
                        <n-input v-model:value="formData.telephone" placeholder="请输入手机号" clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="1" label="邮箱" path="email">
                        <n-input v-model:value="formData.email" placeholder="请输入邮箱" clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="2" label="联系地址" path="address">
                        <n-input v-model:value="formData.address" placeholder="请输入联系地址" clearable />
                    </n-form-item-gi>
                    <n-form-item-gi :span="2" label="备注" path="remark">
                        <n-input v-model:value="formData.remark" placeholder="请输入备注" clearable />
                    </n-form-item-gi>
                </n-grid>
            </n-form>
            <template #footer>
                <n-space justify="end">
                    <n-button v-if="title === '个人信息'" @click="openUserInfoEdit">修改</n-button>
                    <n-button v-if="title !== '个人信息'" @click="cancelUserInfoEdit">取消</n-button>
                    <n-button v-if="title !== '个人信息'" @click="submit">保存</n-button>
                </n-space>
            </template>
        </n-card>

    </div>
</template>

<style scoped></style>